package org.pro.system.config;

import java.util.Date;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.pro.base.domain.SysUrl;
import org.pro.system.service.SysUrlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
/**
 * 已弃用
 * 将所有的 RequestMappingHandlerMapping 映射添加到数据库中
 * 在添加flyway插件之后，会在flyway插件执行之前运行，导致第一次初始化数据库失败
 * 将功能转移到 SysUrlSmartLifecycle 类中
 * @author luoqiz
 *
 */
//@Component
public class SysUrlHandler {
	@Autowired
	public SysUrlService  sysUrlService;
	@Autowired
	public RequestMappingHandlerMapping requestMappingHandlerMapping;
	@PostConstruct
	private void run() {
		Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
		Set<RequestMappingInfo> mappings = map.keySet();
		// Map<String, String> reversedMap = new HashMap<String, String>();
		for (RequestMappingInfo info : mappings) {
			
			PatternsRequestCondition prc = info.getPatternsCondition();  
            Set<String> patterns = prc.getPatterns();  
            StringBuilder urls=new StringBuilder();
            for (String uStr : patterns) {
                 System.out.println(uStr);
                 urls.append(uStr);
            }
            SysUrl sysurl =  new SysUrl();
            sysurl.setAuthority("sys");
            sysurl.setCreateTime(new Date());
            sysurl.setEffective(true);
            sysurl.setType("url");
            sysurl.setUrlPath(urls.toString());
            sysurl.setUrlName(info.getName()==null?"":info.getName());
            sysurl.setUrlController(info.getMethodsCondition().toString());
            //sysUrlService.saveRecord(sysurl);
            sysUrlService.updateOrInsert(sysurl);
//			System.out.println(info.getName());
//			HandlerMethod method = map.get(info);
//			String methodstr = method.toString();
//			methodstr = methodstr.split("\\(")[0];
//			methodstr = methodstr.split(" ")[2];
//			int i = methodstr.lastIndexOf(".");
//			methodstr = methodstr.substring(0, i);
//			String urlparm = info.getPatternsCondition().toString();
//			String url = urlparm.substring(1, urlparm.length() - 1);
//			System.out.println("url-->" + url);
		}
	}
}
